// 货位码维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Switch, message, Pagination, Input  } from 'antd';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import Moment from 'moment';
import store from 'store';
import './style/index.less';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const formItemSpan = {    // label 和input宽度
    labelCol: { span:12 },
    wrapperCol: { span: 12 },
};

const StkBinCodestkBinCodeMaintain = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                WaListData: [], //库存单数据
                SelectCode: [],
                pageSize: 10,
                page: 1,
                total:0,
                stateID: '',
                modalData:[],
                ModalRowData: {}, // 弹框双击选中行数据
                count: '',
                selectedRows: [], //选中行的数据
                selectedRowKeys: [], //选中行的key
                columns:[],
                columnsWidth:'',
                language : JSON.parse(window.sessionStorage.userData),
                ChineseEnglishSize:{}
            };
            // 库存单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '货位名称',
                    dataIndex: 'stkBinDesc',
                    align: "center",
                    width: '25%',
                    render: (text, record,index) => {
                        return(  <Input min={0}  value={text}   onChange={(e) => this.handleFieldChange(e, 'stkBinDesc',record.key)} />)
                    }
                },
                {
                    key: 2,
                    title: '货位代码',
                    dataIndex: 'stkBinCode',
                    align: "center",
                    width: '25%',
                    render: (text, record,index) => {
                        return(  <Input min={0}  value={text}   onChange={(e) => this.handleFieldChange(e, 'stkBinCode',record.key)} />)
                    }
                },
                {
                    key: 3,
                    title: '',
                    dataIndex: 'maxQty',
                    align: "center",
                    width: '25%',
                },
                {
                    key: 4,
                    title: '',
                    dataIndex: 'maxQty',
                    align: "center",
                    width: '25%',
                },


            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getBoundList();
            this.onChangeSelect();
            this.getColumnsChineseAndEnglish();
        }

        // 获取表单与form英语
	    getColumnsChineseAndEnglish = () => {
        let {language} = this.state;
        let data = {
            params: [{
                reactCode: ['CargoCodeMaintenance'],
                compontName: 'CargoCodeMaintenance',
                type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div>{language.language== 'EN' ? item.enDescripts : item.title}</div>,
                                render: (text, record,index) => {
                                    return(  <Input min={0}  value={text}   onChange={(e) => this.handleFieldChange(e, item.code,record.key)} />)
                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, columnsWidth: res.totalWidth,ChineseEnglishSize:language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            });
        };

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state,callback)=>{ return; }
        }

        //获取操作行数据对象
        getRowByKey(key, newData) {
            const { WaListData } = this.state;
            return (newData || WaListData).filter(item => item.key === key)[0];
        }

        //文本框数据修改
        handleFieldChange=(e, fieldName, key)=>{
            const { WaListData} = this.state;
            const newData = WaListData.map(item => ({ ...item }));
            const target = this.getRowByKey(key, newData);
            if (target) {
                target[fieldName] = e.target.value;
                this.setState({WaListData: newData});
            }
        };

        //清空表格内容
        handleReset = () => {
            this.setState({WaListData: [],total: 0,selectedRows: [], selectedRowKeys: []});
            this.onChangeSelect(this.state.userInfo.locID);
            this.props.form.resetFields();
        };


        onRef = (ref) => {
            this.child = ref;
        };


        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02020197",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({SelectData: res})
                    }
                }
            })
        }

        dataQuery=()=>{
            this.setState({page: 1},()=>{
                this.getBoundList()
            })
        }

        // 获取库存单列表数据
        getBoundList=()=>{
            this.setState({loading: true})
            this.props.form.validateFields((error, value)=> {
                let obj = JSON.parse(JSON.stringify(value));
                if(error == null){
                    let data = {
                        params: [{
                            locID: obj.Loc ? obj.Loc : undefined,
                            stkBinID: obj.stkCat ? obj.stkCat : undefined,
                        }],
                        pagination: [
                            {
                                pageSize:this.state.pageSize,
                                currentPage:this.state.page,
                                sort:"ID",
                                dir:"asc",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02020199",
                        data: data,
                        success: function (res) {
                            if(res.errorCode == 0){
                                for(let i = 0; i < res.rows.length; i++){
                                    res.rows[i].key = i;
                                }
                                this.setState({ WaListData: res.rows, total: res.total,selectedRows: [], selectedRowKeys: [], loading: false});

                            }else {
                                this.setState({ WaListData: []});

                            }
                        },
                        error: function (err) {
                            message.error(err.errorMessage)
                        }
                    });
                }
            })
        };

        // 保存
        save=()=>{
            if(this.state.WaListData.length>0){
             for(var i = 0; i< this.state.WaListData.length; i++){
                 this.state.WaListData[i].locID = this.props.form.getFieldValue('Loc');
             }
            }
            this.props.form.validateFields((error, value)=> {
                if(error == null){
                    let data = {
                        params:  this.state.WaListData ? this.state.WaListData : undefined
                    };
                    $http.post('urlS', this, {
                        code: "02020198",
                        data: data,
                        success: function (res) {
                            if(res.errorCode == 0){
                                message.success(res.errorMessage);
                                this.getBoundList();
                            }
                        },
                        error: function (err) {
                            message.error(err.errorMessage)
                        }
                    });
                }
            })
        };

        // 页码改变的回调，参数是改变后的页码及每页条数 库存单
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: this.state.pageSize}, () => {
                // 重新调用查询方法
                this.getBoundList();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        };

        //新增数据
        handleAdd=()=>{
            const { count , WaListData } = this.state;
            const newData = {
                 locID : this.props.form.getFieldValue('Loc'),
                stkBinCode :'',
                stkBinDesc:'',
                key:  WaListData.length
            };
            this.setState({
                WaListData: [...WaListData, newData],
                count: WaListData.length+1
            });
        };
        //删除
        handleDelete=()=>{
            let {ChineseEnglishSize} = this.state;
            if(this.state.selectedRows.length==0){
                message.error(ChineseEnglishSize.CargoCodeMaintenancechooseToDeleteDate ? ChineseEnglishSize.CargoCodeMaintenancechooseToDeleteDate.descripts:'请选择删除对象');
                return
            }
            let arr  = [];
            for(var i = 0; i<this.state.selectedRows.length; i++){
                // arr.stkBinID=this.state.selectedRows[i].stkBinID;
                arr.push({
                    stkBinID:this.state.selectedRows[i].stkBinID
                })
            }
            let data = {
                params: arr.length>0 ? arr : undefined
            };
            $http.post('urlS', this, {
                code: "02020243",
                data: data,
                success: function (res) {
                    if(res.errorCode == 0){
                        arr = [];
                        message.success(res.errorMessage);
                        this.dataQuery();
                    }
                }
            });
        };
        onChangeSelect=(id)=>{
            this.props.form.validateFields((error, value)=> {
                let obj = JSON.parse(JSON.stringify(value));
                if(error == null){
                    let data = {
                        params: [{
                            locID:id ? id: obj.Loc ? obj.Loc : undefined,
                        }],
                        pagination: [
                            {
                                pageSize:this.state.pageSize,
                                currentPage:this.state.page,
                                sort:"ID",
                                dir:"asc",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02020199",
                        data: data,
                        success: function (res) {
                            if(res.errorCode == 0){
                                for(let i = 0; i < res.rows.length; i++){
                                    res.rows[i].key = i;
                                }
                                this.setState({ SelectCode: res.rows});

                            }else {
                                this.setState({ SelectCode: []});

                            }
                        }
                    });
                }
            })
        }
        render() {
            let {ChineseEnglishSize,columns} = this.state;
            const { getFieldDecorator } = this.props.form;
            //库存科室列表
            let inOpLocDrSelect = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            const rowSelection = {
                selectedRowKeys: this.state.selectedRowKeys,
                selectedRows: this.state.selectedRows,
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({selectedRows,selectedRowKeys})
                },
                getCheckboxProps: record => ({
                    disabled: record.linkFlag === 1,
                }),
            };
            return (
                <div className="stkBinCodestkBinCodeMaintain">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.CargoCodeMaintenancelocationCodeMaintenance ? ChineseEnglishSize.CargoCodeMaintenancelocationCodeMaintenance.descripts:'货位码维护'}</div>}
                        >
                            <Col span={18}>
                                <Form>
                                    <Row >
                                        <Col span={8}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.CargoCodeMaintenanceloc ? ChineseEnglishSize.CargoCodeMaintenanceloc.descripts:'科室'}>
                                                {getFieldDecorator('Loc',{
                                                    initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
                                                    rules:[{ required : ChineseEnglishSize.CargoCodeMaintenanceloc ? ChineseEnglishSize.CargoCodeMaintenanceloc.required =='Y'? true:false: false, message: ChineseEnglishSize.CargoCodeMaintenanceloc ? ChineseEnglishSize.CargoCodeMaintenanceloc.message:'科室不能为空'}] 
                                                })(
                                                    <Select allowClear onSelect={this.onChangeSelect}>
                                                        {inOpLocDrSelect}
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={8}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.CargoCodeMaintenancestkCat ? ChineseEnglishSize.CargoCodeMaintenancestkCat.descripts:'货位'}>
                                                {getFieldDecorator('stkCat',{
                                                    initialValue: undefined,
                                                    rules:[{required: false,message: '货位不能为空'}]
                                                })(
                                                    <Select allowClear>
                                                        {this.state.SelectCode.length>0 && this.state.SelectCode.map((item, i) => {
                                                            return <Option value={item.stkBinID} key={i}>{item.stkBinDesc}</Option>
                                                        })}
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={6}>
                                <Row style={{margin: '5px 0 18px'}} className="button">
                                    <Button style={{marginLeft: '20px'}} onClick={this.dataQuery}>{ChineseEnglishSize.CargoCodeMaintenancesearch ? ChineseEnglishSize.CargoCodeMaintenancesearch.descripts:'查询'}</Button>
                                    <Button type="primary" style={{margin: '0 25px'}} onClick={this.handleReset}>{ChineseEnglishSize.CargoCodeMaintenanceclean ? ChineseEnglishSize.CargoCodeMaintenanceclean.descripts:'清屏'}</Button>
                                    <Button type="primary" onClick={this.save}>{ChineseEnglishSize.CargoCodeMaintenancesave ? ChineseEnglishSize.CargoCodeMaintenancesave.descripts:'保存'}</Button>
                                    <Button onClick={this.handleAdd }  style={{marginLeft: '20px'}} >{ChineseEnglishSize.CargoCodeMaintenanceadd ? ChineseEnglishSize.CargoCodeMaintenanceadd.descripts:'新增'} </Button>
                                    <Button onClick={this.handleDelete }  style={{marginLeft: '20px'}} > {ChineseEnglishSize.CargoCodeMaintenancedelete ? ChineseEnglishSize.CargoCodeMaintenancedelete.descripts:'删除'}</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.CargoCodeMaintenancecargoLocInfo ? ChineseEnglishSize.CargoCodeMaintenancecargoLocInfo.descripts:'货位信息'}</div>}
                            >
                                <div  style={{height: store.getState().tableHeight.y +60 + 'px'}}>
                                    <Table
                                        rowSelection={rowSelection}
                                        columns={columns.length>0?columns:this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        style={{height: store.getState().tableHeight.y + 15 + 'px'}}
                                        scroll={{ y: store.getState().tableHeight.y - 85 }}
                                        rowKey={record => record.key}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.WaListData}
                                                      loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                </div>
            )
        }
    }
);
export default StkBinCodestkBinCodeMaintain;